package DEMO;

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @author Lzm
 * @version 1.0
 */
public class BlockingQueueTest {

  public static void main(String[] args) {
    BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);

    // 创建生产者和消费者对象
    Producer p = new Producer(queue);
    Customer c1 = new Customer(queue);
    Customer c2 = new Customer(queue);
    Customer c3= new Customer(queue);
    // 开启线程进行工作
    new Thread(p).start();
    new Thread(c1).start();
    new Thread(c2).start();
    new Thread(c3).start();
    // 当队列满时, 生产者就不会进行生产
    // 当队列空时, 消费者就不会进行消费
  }


}
class Producer implements Runnable{
  private BlockingQueue<Integer> queue;
  public Producer(BlockingQueue queue){
    this.queue = queue;
  }

  @Override
  public void run() {
    for (int i = 0 ; i < 100 ; i++){
      try {
        queue.put(i);
        Thread.sleep(20);
        System.out.println("生产者" + Thread.currentThread().getName() + "生产" + queue.size());
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}
class Customer implements Runnable{
  private BlockingQueue<Integer> queue;
  public Customer(BlockingQueue queue){
    this.queue = queue;
  }

  @Override
  public void run() {
    while(true){
      try {
        queue.take();
        Thread.sleep(new Random().nextInt(1000));
        System.out.println("消费者" + Thread.currentThread().getName() + "消费" + queue.size());
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}
